package com.example.hospitaltraining.exception;


import com.example.hospitaltraining.common.R;
import lombok.Data;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常处理器
     * @ExceptionHandler相当于controller的@RequestMapping
     * 如果抛出的的是ServiceException，则调用该方法
     * @param se 业务异常
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public R handle(ServiceException se){
        return R.error(se.getMessage());
    }

    /**
     * 自定义异常
     */
    @Data
    public static class ServiceException  extends RuntimeException{

        private String code;

        public ServiceException(String code, String message) {
            super(message);
            this.code = code;
        }
    }
}
